from django.http import HttpResponse
from django.utils.timezone import make_aware
from django.db.models import Sum

from ...utils.data_handle import chatpowerlogs_handler
from ...models.powerlogs import PowerLogs

from datetime import datetime, timedelta
import json


def powerlog_list(request):
    '''
    POST
    获取所有的算力日志
    {
        "model": "qwen-plus",
        "date": [
            "2024-08-05",
            "2024-08-20"
        ],
        "type": 1,
        "page": 1,
        "page_size": 20
    }

    type:
    (0) // 获取全部
    (1) // 充值
    (2) // 消费
    (3) // 任务（SD,MJ）执行失败，退款
    (4) // 邀请奖励
    (5) // 众筹
    (6) // 系统赠送
    (7) // 兑换码
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        search_dict = dict()
        total_power = 0
        if "model" in json_obj and json_obj['model']:
            search_dict["model"] = json_obj['model']

        if json_obj['date'] and len(json_obj['date']) == 2:
            start_date = make_aware(datetime.strptime(json_obj['date'][0], "%Y-%m-%d"))
            end_date = make_aware(datetime.strptime(json_obj['date'][1], "%Y-%m-%d")) + timedelta(days=1)

            search_dict["created_at__gte"] = start_date
            search_dict["created_at__lte"] = end_date

            total_power = PowerLogs.objects.filter(created_at__gte=start_date, created_at__lte=end_date).aggregate(sum=Sum('amount'))['sum'] or 0

            # total_power = PowerLogs.objects.aggregate(sum=Sum('amount'))['sum']
            

        typenum = (0, 1, 2, 3, 4, 5, 6, 7)
        if "type" in json_obj and json_obj["type"] in typenum:
            if json_obj["type"] > 0:
                search_dict["type"] = json_obj['type']

        all_chatpowerlogs = PowerLogs.objects.filter(**search_dict).order_by('-id')
        all_chatpowerlogs_data = chatpowerlogs_handler(all_chatpowerlogs, json_obj['page'], json_obj['page_size'])

        res_mes = {
            "code": 0,
            "data": {
                "data": all_chatpowerlogs_data,
                "stat": total_power
            }
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

